package img

import (
	"encoding/base64"
	"errors"
	"fmt"
	"gitee.com/hubdev/api/pkg/app"
	"gitee.com/hubdev/api/pkg/meta"
	"gitee.com/pkg/root"
	"gitee.com/runx/gitctl/pkg/api/conf"
	v1 "gitee.com/runx/gitctl/pkg/api/v1"
	"gitee.com/runx/gitctl/pkg/cli"
	getv1 "gitee.com/runx/gitctl/pkg/cli/get"
	"gitee.com/runx/gitctl/pkg/cli/ops"
	"gitee.com/runx/gitctl/pkg/cli/update"
	"github.com/spf13/cobra"
	"gopkg.in/yaml.v2"
)

var (
	xConf  string
	ns     string
	xCli   *cli.Cli
	getCmd = &cobra.Command{
		Use:   "img",
		Short: "gitctl img -n adx gitea cfxl/gitea:latest",
		RunE: func(c *cobra.Command, args []string) error {
			if len(args) == 0 {
				return errors.New("you need set name args")
			}
			return Update(ns, args)
		},
	}
)

func init() {
	homer, _ := conf.Home()
	getCmd.PersistentFlags().StringVarP(&ns, "namespace", "n", "default", "set resource namespace")
	getCmd.PersistentFlags().StringVarP(&xConf, "config", "c", homer+"/.gitops/config", "tool config file ")
	config := &conf.Config{}
	err := yaml.Unmarshal(conf.GetData(xConf), config)
	if err != nil {
		panic(err)
	}
	xCli = cli.New(config)
	root.AddCmd(getCmd)
}

func Update(namespace string, args []string) error {
	var err error
	resName := args[0]

	res := &v1.Resource{
		Kind: "app",
		Metadata: &meta.Metadata{
			Name:      resName,
			Namespace: namespace,
		},
	}
	ctx := xCli.NewCtx(ops.GetFile, res)

	rsp := &getv1.Content{}
	if err = ctx.Invoke(rsp); err != nil {
		return err
	}
	var data []byte
	if data, err = base64.StdEncoding.DecodeString(rsp.Content); err != nil {
		return err
	}
	appInfo := &app.App{}

	if err = yaml.Unmarshal(data, appInfo); err != nil {
		return err
	}
	appInfo.Status = meta.NewStatus()
	for i, param := range args {
		if i == 0 {
			continue
		}
		appInfo.Spec.Services[i-1].Image = param
	}
	if data, err = yaml.Marshal(appInfo); err != nil {
		return err
	}
	res.Sha = rsp.Sha
	res.Content = string(data)
	ctx = xCli.NewCtx(ops.UpdateFile, res)
	rsp2 := &update.Content{}
	ctx.Invoke(rsp2)
	fmt.Println(rsp2)
	return nil
}
